﻿using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace echuCMS
{
    public partial class FormOrganization : Form
    {
        private BindingSource bsSalesMan = new BindingSource();
        private TreeNode currentNode;
        public FormOrganization()
        {
            InitializeComponent();
        }

        private void FormOrganization_Shown(object sender, EventArgs e)
        {
            //加载左侧树
            LoadTreeView();
        }

        private void FormOrganization_Load(object sender, EventArgs e)
        {
            dataGridViewSalesMan.AutoGenerateColumns = false;
        }

        private void LoadTreeView()
        {
            treeViewOrg.Nodes.Clear();
            //获取所有省市
            List<Provinces> provincesList = getAllProvinces();
            
            //渲染省市节点
            if (provincesList != null && provincesList.Count > 0)
            {
                //渲染省
                for (int i = 0; i < provincesList.Count; i++)
                {
                    TreeNode treeNode = this.treeViewOrg.Nodes.Add(provincesList[i].provinceid.ToString(), provincesList[i].province, 0, 1);
                    treeNode.Tag = "省";
                    if (provincesList[i].cityList != null && provincesList[i].cityList.Count > 0)
                    {
                        //渲染市
                        List<City> cities = provincesList[i].cityList;
                        foreach (var city in cities)
                        {
                          TreeNode node =  treeNode.Nodes.Add(city.cityid,city.city,0,1);
                            node.Tag = "市";
                            //渲染市下面的事业部
                            if (city.organizationCityList != null && city.organizationCityList.Count > 0)
                            {
                                foreach (var org in city.organizationCityList)
                                {
                                   TreeNode n = node.Nodes.Add(org.Id.ToString(), org.SalesOrganization, 2, 2);
                                    n.Tag = "事业部";
                                }
                            }
                        }
                    }
                }
            }
        }


        private List<Provinces> getAllProvinces()
        {
          return OrgService.GetProvinces();
        }

        /// <summary>
        /// 点击事业部节点，显示其所属业务员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeViewOrg_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //添加事业部
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                currentNode = treeViewOrg.GetNodeAt(ClickPoint);
                //TreeNode CurrentNode = tree_materialType.GetNodeAt(ClickPoint);
                if (currentNode != null && (currentNode.Tag.ToString() == "市" || currentNode.Tag.ToString() == "省"))//判断你点的是不是一个节点
                {
                    currentNode.ContextMenuStrip = contextMenuStrip1;
                    //name = tree_materialType.SelectedNode.Text.ToString();//存储节点的文本
                    treeViewOrg.SelectedNode = currentNode;//选中这个节点
                }
            }

            //点击的是事业部，则查询该事业部所有人员
            if (e.Button == MouseButtons.Left)
            {
                if (e.Node.Tag != null && e.Node.Tag.ToString() == "事业部")
                {
                    currentNode = e.Node;
                    int orgId = int.Parse(e.Node.Name);
                    List<SalesMan> salesManList = SalesManService.getSalesManByOrgId(orgId);
                    bsSalesMan.DataSource = salesManList;
                    this.dataGridViewSalesMan.DataSource = bsSalesMan;
                    //查询这个事业部的主管
                    List<OrganizationManager> organizationManagers = SalesManService.getOraManager(orgId);
                    if (organizationManagers != null && organizationManagers.Count > 0)
                    {
                        foreach (DataGridViewRow salesManRow in dataGridViewSalesMan.Rows)
                        {
                            foreach (var manager in organizationManagers)
                            {
                                if (salesManRow.Cells["Cid"].Value.ToString().Equals(manager.ManagerId.ToString()))
                                {
                                    salesManRow.Cells["C职务"].Value = "主管";
                                }
                                else
                                {
                                    salesManRow.Cells["C职务"].Value = "业务员";
                                }
                            }
                        }
                    }
                    else
                    {
                        //没有主管，那就全是业务员
                        foreach (DataGridViewRow salesManRow in dataGridViewSalesMan.Rows)
                        {
                            salesManRow.Cells["C职务"].Value = "业务员";
                        }
                    }
                }
            }
        }

        private void dataGridViewSalesMan_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridViewSalesMan.BeginEdit(true);
        }

        private void dataGridViewSalesMan_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.Value is City)
            {
                e.Value = (e.Value as City).city;
            }
        }

        private void dataGridViewSalesMan_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            SalesMan salesMan = bsSalesMan.Current as SalesMan;
            //更新业务员
            SalesManService.updateSalesMan(salesMan);
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (currentNode == null || currentNode.Tag.ToString() != "事业部")
            {
                MessageBox.Show("请选择需要添加业务员的事业部");
                return;
            }
            SalesMan salesMan = new SalesMan();
            if (string.IsNullOrEmpty(textBoxSalesCode.Text.Trim()))
            {
                MessageBox.Show("业务员编号不可为空");
                return;
            }
            else
            {
                salesMan.SalesManCode = textBoxSalesCode.Text.Trim();
            }

            if (string.IsNullOrEmpty(textBoxSalesName.Text.Trim()))
            {
                MessageBox.Show("业务员编号不可为空");
                return;
            }
            else
            {
                salesMan.SalesManName = textBoxSalesName.Text.Trim();
            }

            if (string.IsNullOrEmpty(textBoxSalesPhone.Text.Trim()))
            {
                MessageBox.Show("业务员编号不可为空");
                return;
            }
            else
            {
                salesMan.SalesManPhone = textBoxSalesPhone.Text.Trim();
            }

            salesMan.SalesManOrgID = int.Parse(currentNode.Name);

            int r = SalesManService.insertSalesMan(salesMan);
            if (r < 0)
            { 
                MessageBox.Show("添加失败，请联系开发者");
            }
            else
            {
                Pub.ClearCntrValue(this);
            }
        }

        private void 添加事业部ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FormAddOrg formAddOrg = new FormAddOrg(currentNode.Text);
            formAddOrg.refresh = LoadTreeView;
            formAddOrg.ShowDialog();
        }

        private void dataGridViewSalesMan_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //删除
            if (dataGridViewSalesMan.Columns[e.ColumnIndex].Name == "C删除")
            {
                if (MessageBox.Show("确认删除？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    SalesMan salesMan = bsSalesMan.Current as SalesMan;
                    int i = SalesManService.deleteSalesMan(salesMan);
                    if (i > 0)
                    {
                        bsSalesMan.RemoveCurrent();
                        bsSalesMan.ResetBindings(true);
                    }
                    else
                    {
                        MessageBox.Show("删除失败，请联系开发者");
                    }
                }
            }
            //设为主管
            if (dataGridViewSalesMan.Columns[e.ColumnIndex].Name == "C设为主管")
            {
                //
                if (MessageBox.Show("确认设为主管？", "设为主管", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    SalesMan salesMan = bsSalesMan.Current as SalesMan;
                    OrganizationManager organizationManager = new OrganizationManager();
                    organizationManager.ManagerId = salesMan.Id;
                    organizationManager.SalesOrganizationId = salesMan.SalesManOrgID;
                  int i =  SalesManService.addManager(organizationManager);
                    if (i > 0)
                    {
                        MessageBox.Show("设置成功");
                    }
                    else
                    {
                        MessageBox.Show("删除失败，请联系开发者");
                    }
                }
            }
        }
    }
}
